package com.haistand.module.common.bmap.service;


import com.alibaba.fastjson.JSON;
import com.haistand.module.common.bmap.vo.Location;
import com.haistand.module.common.bmap.vo.BMapResponse;
import com.haistand.module.common.utils.HttpUtil;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.lang3.StringUtils;

public class BmapService{

    static final String BMAP_URL = "http://api.map.baidu.com/geocoder/v2/";

    static final String ak = "64b397b529af28b505f515817f072324";

    static final String output = "json";

    private static BmapService bmapServiceImpl;

    private BmapService() {
    }

    public static synchronized BmapService getInstance() {
        if (bmapServiceImpl == null) {
            bmapServiceImpl = new BmapService();
        }
        return bmapServiceImpl;
    }

    /**
     * 地图接口 的调用
     */
    public BMapResponse getLocation(String address) {
        NameValuePair[] params = {new NameValuePair("address", address),
                new NameValuePair("ak", ak),
                new NameValuePair("output", output)};
        BMapResponse mapResponse = null;
        String result = HttpUtil.post(BMAP_URL, params);
        mapResponse = JSON.parseObject(result, BMapResponse.class);
        return mapResponse;
    }

    /**
     * 根据地址关键字查询坐标
     *
     * @param addressKeyword
     * @return
     */
    public Location getLocationByAddress(String addressKeyword) {
        BMapResponse bMapResponse = getLocation(addressKeyword);
        if (bMapResponse != null && StringUtils.isNoneBlank(bMapResponse.getStatus()) && bMapResponse.getStatus().equals("0")) {
            return bMapResponse.getResult().getLocation();
        } else {
            System.out.println("--------------No search results!----------------");
            return null;
        }
    }

    public static void main(String[] args) {
        BmapService bmapServiceImpl = BmapService.getInstance();
        BMapResponse bMapResponse = bmapServiceImpl.getLocation("岳阳市八字门");
        if (bMapResponse != null && bMapResponse.getStatus().equals("0")) {
            System.out.println(bMapResponse.getResult().getLocation().getLat() + " " + bMapResponse.getResult().getLocation().getLng() + " "
                    + bMapResponse.getResult().getPrecise() + " "
                    + bMapResponse.getResult().getLevel() + " "
                    + bMapResponse.getResult().getConfidence());
        } else {
            System.err.println("没有搜寻结果");
        }

    }
}
